<template>
  <view class="mineInfo">
    <view class="flex_p_20">
      <uv-form ref="formRef" :form="form" :rules="rules" labelWidth="110px" errorType="border-bottom">
        <uv-form-item label="姓名" prop="name" borderBottom required>
          <uv-input v-model="form.name" placeholder="请输入姓名" input-align="right" border="none"></uv-input>
        </uv-form-item>
        <uv-form-item label="手机号" prop="phone" borderBottom required>
          <uv-input v-model="form.phone" placeholder="请输入手机号" disabled-color="transparent" input-align="right" border="none"></uv-input>
        </uv-form-item>
        <uv-form-item label="所属公司" prop="companyName" borderBottom required>
          <uv-input v-model="form.companyName" placeholder="请输入所属公司" disabled disabled-color="transparent" input-align="right" border="none"></uv-input>
        </uv-form-item>
        <uv-form-item label="头像" prop="image">
          <view class="flex_1 flex flex_x_end">
            <view style="width: 180rpx;">
              <uv-upload
                  :fileList="fileList1"
                  name="1"
                  :maxCount="1"
                  @afterRead="afterRead"
                  @delete="deletePic"
              ></uv-upload>
            </view>
          </view>
        </uv-form-item>
      </uv-form>
      <view class="flex_h_30"></view>
    </view>
    <view class="flex_1 lastBtn">
      <uv-button type="primary" color="#2D4C98" shape="circle" @click="submitForm">确认提交</uv-button>
    </view>
  </view>
</template>

<script>
import config from "@/config";
import UserInfoApi from "@/api/system/userInfo";
import {getToken, getUserInfoId} from "@/utils/auth";

export default {
  data() {
    return {
      upImg: [],
      baseURL: config.baseUrl,
      userId: null,
      fileList1: [],
      info: {},
      form: {
        id: null,
        name: null,
        phone: null,
        image: null,
      },
      rules: {},
    };
  },
  onLoad() {
    this.userId = getUserInfoId();
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      const data = await UserInfoApi.getUserProfile(this.userId);
      this.info = data?.data;
      this.form = {
        id: this.info.id,
        name: this.info.name,
        phone: this.info.phone,
        image: this.info.image,
        companyName: this.info.companyName
      };
      if (this.info.image) {
        this.fileList1 = [{
          url: this.info.image
        }]
      }
    },
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i],'image')
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    uploadFilePromise(file, type) {
      const _this = this
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          header: {
            'Authorization': 'Bearer ' + getToken(),
          },
          url: _this.baseURL + '/resource/oss/upload',
          filePath: file.url,
          name: 'file',
          formData: {
            file: file
          },
          success: (res) => {
            setTimeout(() => {
              const json = JSON.parse(res.data);
              console.log('6666---->>>,',json);
              if (type === 'image') {
                this.upImg.push(json.data?.ossId);
              }
              resolve(res.data.data)
            }, 1000)
          }
        });
      })
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    submitForm() {
      this.$refs.formRef.validate().then(async () => {
        if (this.upImg.length > 0) {
          this.form.image = this.upImg.join(',');
        }
        UserInfoApi.updateUser(this.form).then(() => {
          uni.showToast( {
            title: '修改成功',
            icon: 'success',
            duration: 2000,
          })
          setTimeout(() => {
            uni.switchTab( {
              url: '/pages/mine/index'
            })
          },2000)
        });
      })
    },
  },
}
</script>

<style scoped lang="scss">
.lastBtn{
  width: 100%;
  padding: 0 20px 0 20px;
  position: fixed;
  bottom: 30px;
}
</style>
